package com.ideal.manage.esms.util;

import com.jcraft.jsch.*;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

/**
 * Created by wanghongbo on 2015/3/20.
 */
public class SftpCustomer {
    private SftpConfig config;
    private ChannelSftp sftp;
    private Session sshSession;

    public SftpCustomer(SftpConfig config) {
        this.config = config;
    }

    public boolean connect() {
        try {
            JSch jsch = new JSch();
            sshSession = jsch.getSession(config.getUser(), config.getHost(), config.getPort());
            sshSession.setPassword(config.getPassword());
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
        } catch (Exception e) {
            e.getStackTrace();
            return false;
        }
        return true;
    }

    public boolean close() {
        sshSession.disconnect();
        sftp.disconnect();
        return true;
    }

    public String[] list(String path, String match) {
        List<String> array = new ArrayList<String>();
        try {
            path = path.replaceAll("\\\\", "/");
            Vector<ChannelSftp.LsEntry> vector = sftp.ls(path);
            for (ChannelSftp.LsEntry lsEntry : vector) {
                String fileName = lsEntry.getFilename();
                if (fileName.matches(match)) {
                    array.add(path + "/" + fileName);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return array.toArray(new String[array.size()]);
    }

    public String download(String source, String dist) throws Exception {
        dist = dist.replaceAll("\\\\", "/");
        int pos = source.lastIndexOf("/");
        String fileName = source.substring(pos + 1);
        sftp.get(source, dist);
        return dist + (dist.endsWith("/") ? StringUtils.EMPTY : "/") + fileName;
    }

    public boolean upload(String sourceFile, String distDirector) {
        java.io.InputStream is = null;
        try {
            File file = new File(sourceFile);
            is = new FileInputStream(file);
            sftp.put(is, distDirector);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    public void delete(String fileName) throws Exception{
        sftp.rm(fileName);
    }
}
